"use strict";

$(function () {
  $("#page").bootstrapPaginator({
    currentPage: page_no,
    totalPages: total_page,
    bootstrapMajorVersion: 3,
    size: "small",
    numberOfPages: 20,
    onPageClicked: function onPageClicked(e, originalEvent, type, page) {
      window.location.href = "/" + db + "?page=" + page + "&keyword=" + keyword;
    }
  });
});

$(function () {
  $('li', '.choose-db').click(function (e) {
    var db = $(this).find('a').data('db');
    if ($(this).find('a').length === 0) {
      db = $(this).data('db');
    }
    location.href = location.origin + '/' + db;
  });
});

// prism 按钮
(function () {
  // modal 弹窗复制
  Prism.plugins.toolbar.registerButton('copy-to-clipboard', function () {
    var linkCopy = document.createElement('a');
    linkCopy.textContent = 'Copy';
    
    linkCopy.addEventListener('click', function () {
      document.getElementById("code-content").select();
      document.execCommand("copy");
      
      linkCopy.textContent = "Copied!";
      layer.msg('已复制到粘贴板');
      resetText();
    });
    
    function resetText() {
      setTimeout(function () {
        linkCopy.textContent = 'Copy';
      }, 5000);
    }
    
    return linkCopy;
  });
  
  // modal 弹窗高亮
  Prism.plugins.toolbar.registerButton('highlight', function () {
    var a = document.createElement('a');
    a.textContent = '高亮';
    
    a.addEventListener('click', function () {
      Prism.highlightAll();
    });
    
    return a;
  });
})();

Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return fmt;
};

// 复制普通文本
function copy(text) {
  var input = document.createElement('input');
  input.setAttribute('value', text);
  document.body.appendChild(input);
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
}

// 复制有换行符的文本
function copyTextarea(text) {
  var textarea = document.createElement('textarea');
  textarea.innerHTML = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}

// 懒加载 (原来的方式返回10条记录的全部信息, 但是很多情况下我们只想查看其中一两条记录)
var lazy_load_logs = {};

function getLogDetail(id) {
  if (lazy_load_logs.hasOwnProperty(id)) {
    return new Promise(function (resolve) {
      return resolve(lazy_load_logs[id]);
    });
  }
  return $.get('_logger_detail/' + db + '?id=' + id, function (response) {
    return response;
  });
}

Vue.config.devtools = true;
list = JSON.parse(list) || [];
// dbs = JSON.parse(dbs) || [];
var current_project = '';
projects.map(function (project) {
  if (project.db === db) {
    current_project = project.name;
  }
});

if (db === '') {
  $('#choose-db').modal("show");
}

// 日期格式转换
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (var _iterator = list[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
    var log = _step.value;
    
    log.created_at = new Date(log.created_at).format("yyyy-MM-dd hh:mm:ss");
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator.return) {
      _iterator.return();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

var app = new Vue({
  el: '#logger',
  data: {
    logs: list,
    keyword: keyword,
    db: db,
    projects: projects,
    current_project: current_project
  },
  methods: {
    // 显示隐藏详情
    toggleDetail: function toggleDetail(log, event) {
      var _id = log._id;
      getLogDetail(_id).then(function (log) {
        return lazy_load_logs[_id] = log;
      });
      // $('#log-' + log.id).toggle();
      $(event.target).next('.detail').toggle();
    },
    
    // 复制普通文本
    copyValue: function copyValue(value) {
      copy(value);
      layer.msg('已复制到粘贴板');
    },
    
    // 显示模态框
    showContent: function showContent(title, log, type) {
      var id = log._id;
      var content = '';
      getLogDetail(id).then(function (log) {
        lazy_load_logs[id] = log;
        
        switch (title) {
          case '请求头':
            var request_header_array = JSON.parse(log.request_header_array);
            var header = {};
            for (let key of Object.keys(request_header_array)) {
              header[key] = request_header_array[key][0];
            }
            content = JSON.stringify(header, null, 2);
            break;
          case '请求参数':
            content = log.request_params;
            break;
          case '响应内容':
            content = log.response_body;
            break;
            case '详情':
              content = '';
              if (log.queries !== undefined) {
                  log.queries.forEach(function (value) {
                      content += "(" + value.duration_str + ") " + value.sql + "\n";
                  })
              }
              break;
        }
        
        // modal 框拖拽
        if (!$('.modal.in').length) {
          $('.modal-dialog').css({
            top: 0,
            left: 0
          });
        }
        $('.modal-dialog').draggable({
          handle: ".modal-header"
        });
        
        $('#code-content').val(content);
        // 设置标题
        $('#modal-title').html(title);
        try {
          content = type == 'json' ? JSON.stringify(JSON.parse(content), null, 2) : content;
        } catch (e) {
          console.log(content);
          layer.msg('非法 json 对象, 打开控制台查看具体内容');
          return;
        }
        $('#modal-content').html(content); // modal 不能直接使用上面的复制方法
        $('#modal').modal('show');
        // 小于 26k 的时候高亮显示, 字符多的时候会卡住
        if (content.length < 26 * 1024) {
          Prism.highlightAll();
        }
      });
    },
    
    // 清空 logger 表
    _clear_log: function _clear_log() {
      $.get('_clear_log', {}, function () {
        location.reload();
      });
    },
    // 清除文档缓存
    _clear_swagger_cache: function _clear_swagger_cache() {
      $.get('_clear_swagger_cache', function () {
        location.reload();
      });
    },
    
    // 点击按钮搜索
    submit: function submit() {
      $('#search-form').submit();
    },
    
    showDocsModal: function showDocsModal() {
      $('#doc-modal').modal('show');
    },
    
    // 复制 curl 代码
    copyCurlCode: function copyCurlCode(log) {
      var id = log._id;
      getLogDetail(id).then(function (log) {
        lazy_load_logs[id] = log;
        
        var content_type = void 0;
        
        function getHeaderString(headers) {
          try {
            headers = JSON.parse(headers);
          } catch (e) {
            return '';
          }
          
          var header_string = '';
          var keys = Object.keys(headers);
          for (var i = 0; i < keys.length; i++) {
            if (keys[i].toLowerCase() === 'content-length') {
              continue;
            }
            
            var value = headers[keys[i]].length >= 1 ? headers[keys[i]][0] : '';
            if (value !== '') header_string += "  -H '" + keys[i] + ": " + value + "' \\\n";
            
            if (keys[i].toLowerCase() === 'content-type') {
              content_type = value;
            }
          }
          
          return header_string;
        }
        
        var header_string = getHeaderString(log.request_header_array);
        
        function getParamString(params, method) {
          if (method === 'GET') {
            return '';
          }
          
          try {
            params = JSON.parse(params);
          } catch (e) {
            return '';
          }
          
          var param_string = '';
          var keys = Object.keys(params);
          for (var i = 0; i < keys.length; i++) {
            var m = '-F';
            if (method === 'POST' && content_type.toLowerCase().indexOf('x-www-form-urlencoded') > 0) {
              m = '-d';
            }
            if (i !== keys.length - 1) {
              param_string += "  " + m + " " + keys[i] + "=" + params[keys[i]] + " \\\n";
            } else {
              param_string += "  " + m + " " + keys[i] + "=" + params[keys[i]];
            }
          }
          
          return param_string;
        }
        
        var param_string = getParamString(log.request_params, log.method);
        
        var curl_code = "curl -X " + log.method + " \\\n  '" + log.full_url + "' \\\n" + header_string + "\n" + param_string + "\n";
        copyTextarea(curl_code);
        layer.msg('已复制到粘贴板');
      });
    }
  },
  computed: {
    methodGet: function methodGet(method) {
      return method === 'GET';
    },
    methodPost: function methodPost(method) {
      return method === 'POST';
    }
  }
});